package com.forlove.app.qselect.index.ui;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.common.widget.SetItemView;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.friend.widget.dialog.ShowInfoDialog;
import com.forlove.app.qselect.index.entity.OfficialEntity;
import com.forlove.app.qselect.index.presenter.SetPresenter;
import com.forlove.app.qselect.index.view.SetView;
import com.forlove.app.qselect.login.entity.LoginEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity;
import com.forlove.app.qselect.login.ui.ValidateCodeActivity;
import com.forlove.app.qselect.login.widget.ResetPwTipDialog;
import com.forlove.app.qselect.update.diaolog.FileDownloadDialog;
import com.forlove.app.qselect.update.entity.UpdateEntity;
import com.forlove.app.qselect.webview.FadeBackActivity;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 设置页面
 * Created by yjl on 2017/10/11.
 */

public class SetActivitty extends BaseActivity<SetPresenter> implements View.OnClickListener, SetView {

    @BindView(R.id.view_set_pw)
    SetItemView view_set_pw;

    @BindView(R.id.view_update)
    SetItemView view_update;

    @BindView(R.id.view_fade_back)
    SetItemView view_fade_back;

    @BindView(R.id.view_about_app)
    SetItemView view_about_app;

    @BindView(R.id.view_candidate)
    SetItemView candidate;

    @BindView(R.id.text_quit)
    TextView viewQuit;

    @BindView(R.id.set_toolbar_back_icon)
    AppCompatImageView set_toolbar_back_icon;

    private ResetPwTipDialog resetPwTipDialog;
    private UserEntity userEntity;
    private FileDownloadDialog fileDownloadDialog; //下载进度的dialog
    private ShowInfoDialog showInfoDialog;
    private static OfficialEntity officialEntity;

    @Override
    public int getLayoutId() {
        return R.layout.activity_set;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new SetPresenter(this);
        }
        view_set_pw.setTitle("更改密码");
        view_update.setTitle("更新版本");
        view_update.setSubtitle(SystemUtils.getAppVersionName(this));
        view_fade_back.setTitle("建议/反馈");
        candidate.setTitle("圈一圈候选人");
        set_toolbar_back_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        userEntity = UserManager.getUesrInfo(this);
        view_set_pw.setItemOnClickListener(this);
        view_fade_back.setItemOnClickListener(this);
        viewQuit.setOnClickListener(this);
        view_update.setOnClickListener(this);
        candidate.setOnClickListener(this);
        if (officialEntity == null) {
            presenter.getOffical();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_set_pw:
                showResetPwTipDialog();
                break;
            case R.id.view_fade_back:
                startActivity(new Intent(this, FadeBackActivity.class));
                break;
            case R.id.text_quit:
                UserManager.Logout();
//                Intent intent = new Intent(this, ChoiceLimitActivity.class);
                Intent intent = new Intent(this, ChoiceNewAgeActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
                break;
            case R.id.view_update:
                String version = SystemUtils.getAppVersionName(this);
                if (!TextUtils.isEmpty(version)) {
                    presenter.checkUpdate(version);
                }
                break;
            case R.id.view_candidate:
                startActivity(new Intent(this, CustomCandidateActivity.class));
                break;
        }
    }

    @OnClick(R.id.view_open_weixin)
    public void openWeixin() {
        if (officialEntity == null
                || !StringUtils.isNotEmpty(officialEntity.WEIXIN)) {
            presenter.getOffical();
            return;
        }
        SystemUtils.copyToClip(officialEntity.WEIXIN, this);
        if (showInfoDialog == null) {
            showInfoDialog = new ShowInfoDialog(this);
        }
//        String spannableString = String.format(String.format(getString(R.string.str_copy_official), officialEntity.WEIXIN));
        String spannableString = "微信号 <font color='#ff3333'>" + officialEntity.WEIXIN + "</font> 已复制到剪贴板,打开微信添加为好友";
        showInfoDialog.setTextMesseage(Html.fromHtml(spannableString));
        showInfoDialog.setCancel("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInfoDialog.dismiss();
            }
        });
        showInfoDialog.setAgree("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent intent1 = new Intent();
                    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                    intent1.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.setComponent(cmp);
                    startActivity(intent1);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(SetActivitty.this, "检查到您手机没有安装微信，请安装后使用该功能", Toast.LENGTH_LONG).show();
                }
            }
        });
        showInfoDialog.show();
    }

    @OnClick(R.id.view_open_qq)
    public void openQQ() {
        if (officialEntity == null || !StringUtils.isNotEmpty(officialEntity.QQ)) {
            presenter.getOffical();
            return;
        }
        SystemUtils.copyToClip(officialEntity.QQ, this);
        if (showInfoDialog == null) {
            showInfoDialog = new ShowInfoDialog(this);
        }
        String spannableString = "QQ号 <font color='#ff3333'>" + officialEntity.QQ + "</font> 已复制到剪贴板,打开QQ添加为好友";
        showInfoDialog.setTextMesseage(Html.fromHtml(spannableString));
        showInfoDialog.setCancel("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInfoDialog.dismiss();
            }
        });
        showInfoDialog.setAgree("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent intent1 = new Intent();
                    ComponentName cmp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.SplashActivity");
                    intent1.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.setComponent(cmp);
                    startActivity(intent1);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(SetActivitty.this, "检查到您手机没有安装QQ，请安装后使用该功能", Toast.LENGTH_LONG).show();
                }
            }
        });
        showInfoDialog.show();
    }


    @OnClick(R.id.view_open_weibo)
    public void openWeiBo() {
        if (officialEntity == null || !StringUtils.isNotEmpty(officialEntity.WEIBO)) {
            presenter.getOffical();
            return;
        }
        try {
            if (SystemUtils.isAvilible(this, "com.sina.weibo")) {
                Intent intent = new Intent();
                ComponentName cmp = new ComponentName("com.sina.weibo", "com.sina.weibo.page.ProfileInfoActivity");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                intent.putExtra("uid", officialEntity.WEIBO);
                startActivity(intent);
            } else {
                Uri uri = Uri.parse("https://m.weibo.cn/u/" + officialEntity.WEIBO);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(it);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showDownloadDialog(final UpdateEntity updateEntity) {
        if (updateEntity != null
                && updateEntity.getStatus() == 200
                && updateEntity.getVesion() > Float.valueOf(SystemUtils.getAppVersionName(this))) {

            if (fileDownloadDialog == null) {
                fileDownloadDialog = new FileDownloadDialog(SetActivitty.this, updateEntity);
            } else {
                fileDownloadDialog.setUpdateEntity(updateEntity);
            }
            fileDownloadDialog.setcancel(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (fileDownloadDialog.isShowing()) {
                        fileDownloadDialog.dismiss();
                        setBackGround(1f);
                    }
                }
            });
            if (!fileDownloadDialog.isShowing()) {
                fileDownloadDialog.show(false);
                setBackGround(0.6f);
            }
        } else {
            Toast.makeText(this, "当前是最新版本", Toast.LENGTH_SHORT).show();
        }
    }

    public void setBackGround(float fot) {
        WindowManager.LayoutParams layout = getWindow().getAttributes();
        float params = layout.alpha = fot;//屏幕亮度变暗
        getWindow().setAttributes(layout);
    }

    private void showResetPwTipDialog() {
        if (resetPwTipDialog == null) {
            resetPwTipDialog = new ResetPwTipDialog(this);
        }
        if (userEntity != null && !TextUtils.isEmpty(userEntity.userMobile)) {
            int lenght = userEntity.userMobile.length();
            if (lenght > 5) {
                String str = userEntity.userMobile.substring(0, 3);
                for (int i = 0; i < (lenght - 3); i++) {
                    str += "*";
                }
                resetPwTipDialog.setTextMesseage("将要发送验证短信到手机号为" + str);
            }
        }
        resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestResetPWPhone();
                resetPwTipDialog.dismiss();
            }
        });
        resetPwTipDialog.show();
    }

    /**
     * 遗忘，重置密码
     */
    private void requestResetPWPhone() {
        LoginEntity loginEntity = new LoginEntity();
        loginEntity.mobile = userEntity.userMobile;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(loginEntity.mobile);
        String time = MyTimeUtils.formatDate(new Date(System.currentTimeMillis()), "yyyyMMdd");
        stringBuilder.append(time);
        String keyCode = CipherUtils.md5(stringBuilder.toString());
        String sign = CryptAES.AES_Encrypt(keyCode, loginEntity.mobile);
        presenter.loadSendMsg(loginEntity, sign);
    }

    @Override
    public void showSendMsgView(LoginEntity loginEntity) {
        Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
        if (loginEntity != null && !TextUtils.isEmpty(loginEntity.message)) {
            Toast.makeText(this, loginEntity.message, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, ValidateCodeActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("phone", userEntity.userMobile);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateOfficialData(OfficialEntity entity) {
        officialEntity = entity;
    }
}
